<template>
  <div>
    <div class="flex flex-col h-full">
      <SearchContainer @reset="() => formRef.resetFields()" @search="getData">
        <a-form ref="formRef" class="form-style-flex" :model="formState">
          <a-form-item name="pyjm">
            <a-input v-model:value="formState.pyjm" class="w-64" placeholder="姓名/助记码/手机号/床位号" />
          </a-form-item>
          <a-form-item name="stdate" label="检验日期" class="mx-3 w-72">
            <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item name="categoryCode" label="检验大类" class="w-64">
            <a-select v-model:value="formState.categoryCode" placeholder="请选择" class="w-40">
              <a-select-option v-for="item in categoryList" :key="item" :value="item.categoryCode">{{ item.categoryName }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </SearchContainer>
      <a-card class="mt-2 flex-1">
        <div class="absolute top-[-9999px] hidden">
          <a-button ref="printMe" v-print="{ id: 'printMe' }">打印</a-button>
          <PrintView id="printMe" :print-data="printData" />
        </div>
        <BaseTable fill :loading="loading" :column-code="columnCode" :data-source="tableData" :scroll="{ x: 2100 }" :pagination="pagination" bordered>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'status'">
              <a-tag v-if="record.status === '0'" color="blue">未审核</a-tag>
              <a-tag v-if="record.status === '1'" color="green">已审核</a-tag>
              <a-tag v-if="record.status === '2'" color="red">已审核</a-tag>
            </template>
            <template v-if="column.dataIndex === 'recordCode'">
              <PopoverTable :config="detailConfig" :params="{ brId: record.brId, lsh: record.lsh, xb: record.brXb }" :width="1000">
                <template #bodyCell="{ column: popColumn, record: popRecord }">
                  <template v-if="popColumn.dataIndex === 'lastResult'">
                    <div class="flex">
                      <div class="mr-5">{{ popRecord.lastResult }}</div>
                      <div class="tip absolute right-4 text-2xl top-2 z-10">
                        <div v-if="popRecord.tips === '1'" class="text-green-500">↓</div>
                        <div v-if="popRecord.tips === '2'" class="text-red-500">↑</div>
                      </div>
                    </div>
                  </template>
                </template>
                {{ record.recordCode }}
              </PopoverTable>
            </template>
            <template v-if="column.dataIndex === 'action'">
              <a-button type="link" size="small" @click="onPrint(record, '1')">预览</a-button>
              <a-button type="link" size="small" @click="onPrint(record, '2')">打印</a-button>
              <a-button type="link" size="small" @click="onExport(record)">导出</a-button>
            </template>
          </template>
        </BaseTable>
      </a-card>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import { post, http } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import PrintView from './PrintView.vue'

const categoryList = ref([])
const printData = ref({})
const printMe = ref()
const formState = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const formRef = ref(null)
const columnCode = ref('000492')
const detailConfig = ref({
  url: '/lis/LisRecord/getLisItemRecordList',
  columnCode: '000186',
  rowKey: 'id',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      NO: index + 1
    }))
  }
})

const { loading, pagination, getData, tableData } = useTable({
  url: '/lis/LisApply/getLisReportList',
  formatParams: () => {
    return {
      applyPath: 1,
      status: 1,
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1],
      pyjm: formState.value?.pyjm,
      categoryCode: formState.value?.categoryCode,
      wardName: formState.value?.wardName,
      lastBedCode: formState.value?.lastBedCode
    }
  }
})

const getCategoryList = async () => {
  const { code, data, msg } = await post('/lis/InstrumentType/getLisCategoryList')
  if (code !== 0) return message.error(msg)
  categoryList.value = data
  // formState.value.categoryCode = data[0]?.categoryCode
}

const onPrint = async (row, dylx) => {
  const { code, msg, data } = await post('/lis/lisPrint/printLisRecord', { lsh: row.lsh, barCode: row.barCode, dylx })
  if (code !== 0) return message.error(msg)
  if (getSystemConfig('NAVYHIS_MODE') === '1') {
    printData.value = JSON.parse(data)
    setTimeout(() => {
      setPrintSize('A5', 'landscape')
      printMe.value.$el.click()
    }, 1000)
  } else {
    window.openExe?.rpt(data) //调用winform打印
  }
}

// 导出
const onExport = (row) => {
  http
    .post(
      '/lis/LisRecord/exportLisReportDetails',
      {
        parameters: {
          brId: row.brId,
          lsh: row.lsh,
          xb: row.brXb
        },
        tblcode: '000186'
      },
      { responseType: 'blob' }
    )
    .then((res) => {
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = '检验报告明细' + '.xlsx'
      element.href = href
      element.click()
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}

onMounted(() => {
  getCategoryList()
  getData()
})
</script>
